/**
 * 
 */
package com.laivi.basic.model.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import com.laivi.basic.common.constants.Constant;
import com.laivi.basic.type.DBType;
import com.laivi.basic.util.LangUtil;

/**
 * @author laivi.zhu@gmail.com
 * @date 2014-7-2
 * description:
 */
public class BasicDBConn implements BasicDB{
	private String url,user,password;
	private Connection conn=null;
	private DBType type;
	private static Set<String> drivers=new HashSet<String>();
	
	public BasicDBConn(String url,String user,String password){
		this.url=url;
		this.user=user;
		this.password=password;
		String driver=null;
		if(url.indexOf("sqlserver")!=-1){
			type=DBType.SQLSERVER;
			driver=Constant.DBDriver.SQLSERVER_JTDS;
		}else if(url.indexOf("oracle")!=-1){
			type=DBType.ORACLE;
			driver=Constant.DBDriver.ORACLE;
		}else{
			type=DBType.MYSQL;
			driver=Constant.DBDriver.MYSQL;
		}
		
		if(!drivers.contains(driver)){
			LangUtil.isExist(driver);
			drivers.add(driver);
		}
	}
	
	public Connection getConn(){
		try {
			conn= DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	@Override
	public void close(Connection conn) {
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public DBType getType() {
		return type;
	}

	@Override
	public String getDataBase() {
		String database=null;
		switch(type){
			case ORACLE:
				database= url.substring(url.lastIndexOf(":")+1, url.length());
				break;
			default:
				database=url.substring(url.lastIndexOf("/")+1, url.length());
				break;
		}
		return database;
	}

	@Override
	public String getUser() {
		return user;
	}

}
